<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue响应式原理</title>
</head>
<body>
    <script>
        // 触发视图更新
        function triggerRender() {
            console.log('视图更新')
        }
        function defineReactive(target = {}) {
            // 判断target类型，如果为非引用类型，则return
            if (typeof target !== 'object' || target == null) {
                return target
            }
            // 代理配置
            const proxyConfig = {
                get(target, key, receiver) {
                    // 判断是否是自身属性
                    if (Reflect.ownKeys(target).includes(key)) {
                        console.log('get', key)
                    }
                    const result = Reflect.get(target, key, receiver)
                    // 返回当前key对应的值
                    // return result
                    // 递归监听子元素对象
                    return defineReactive(result)
                },
                set(target, key, value, receiver) {
                    const ownKeys = Reflect.ownKeys(target)
                    if (value !== target[key]) {
                        console.log('set', key, value)
                    }
                    if (ownKeys.includes(key)) {
                        console.log('已有属性')
                    } else {
                        console.log('新增属性')
                    }
                    const result = Reflect.set(target, key, value, receiver)
                    // 返回true false表示是否设置成功
                    return result
                },
                deleteProperty(target, key) {
                    console.log('delete', key)
                    const result = Reflect.deleteProperty(target, key)
                    // 返回true false表示是否设置成功
                    return result
                }
            }
            const observed = new Proxy(target, proxyConfig)
            return observed
        }
        const data = {
            name: '张三',
            age: 20,
            test: {
                a: {
                    b: {
                        c: 1
                    }
                }
            }
        }
        // const data = [1, 2, 3]
        const proxyData = defineReactive(data)
        // console.log(proxyData.test)
        // console.log(proxyData.test.a)
        // proxyData.push(4)
        // console.log(proxyData)
        proxyData.name = '李四'
        proxyData.address = '上海'
        // Reflect.deleteProperty(proxyData, 'age')
        // console.log(proxyData)
        // console.log(proxyData.__proto__)
        // console.log(proxyData.test)
        // console.log(proxyData.test.a)
    </script>
</body>
</html>
